import { Checkbox, Divider, Modal } from 'antd'
import { useState } from 'react'
import _ from 'lodash'
import { callExportList, callExportQuery } from '../api/companyList'
import { message } from '@hs-admin/utils'

const CheckboxGroup = Checkbox.Group
interface Props {
  requestParams: any
  dataTotal: number
}
const useExportCompanyListModal = (props: Props) => {
  const { requestParams, dataTotal } = props
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [checkedList, setCheckedList] = useState<string[][]>([[], [], [], [], [], []])
  const dataList: any[] = [
    {
      label: '基本信息',
      value: '基本信息',
      checkAll: checkedList[0].length === 23,
      indeterminate: checkedList[0].length > 0 && checkedList[0].length < 23,
      children: [
        { label: '公司名称', value: 'company_name' },
        { label: '经营状态', value: 'business_state' },
        { label: '统一社会信息用代码', value: 'uni_code' },
        { label: '法定代表人', value: 'legal_rep' },
        { label: '成立时间', value: 'found_date' },
        { label: '注册资本（人民币）', value: 'regcapital_amt_cal' },
        { label: '公司地址', value: 'reg_address' },
        { label: '省份', value: 'province' },
        { label: '城市', value: 'city' },
        { label: '区县', value: 'area' },
        { label: '实缴资本（人民币）', value: 'paied_amt' },
        { label: '纳税人识别号', value: 'tax_code' },
        { label: '注册号', value: 'reg_code' },
        { label: '组织机构代码', value: 'org_code' },
        { label: '纳税人资质', value: 'tax_qualified' },
        { label: '公司类型', value: 'company_type' },
        { label: '公司性质', value: 'company_nature' },
        { label: '国民经济行业分类', value: 'industry_nea' },
        { label: '登记机关', value: 'register_org' },
        { label: '曾用名', value: 'name_before' },
        { label: '英文名', value: 'company_name_en' },
        { label: '企业简介', value: 'describer' },
        { label: '经营范围', value: 'business_scope' }
      ]
    },
    {
      label: '2023年经营数据',
      value: '2023',
      checkAll: checkedList[1].length === 6,
      indeterminate: checkedList[1].length > 0 && checkedList[1].length < 6,
      children: [
        { label: '主营业务收入规模（万元）', value: '2023|prime_bus_profit' },
        { label: '营收规模（万元）', value: '2023|total_sales' },
        { label: '总利润规模（万元）', value: '2023|total_profit' },
        { label: '净利润规模（万元）', value: '2023|retained_profit' },
        { label: '资产总额规模（万元）', value: '2023|total_assets' },
        { label: '负债总额规模（万元）', value: '2023|total_liability' }
      ]
    },
    {
      label: '2022年经营数据',
      value: '2022',
      checkAll: checkedList[2].length === 6,
      indeterminate: checkedList[2].length > 0 && checkedList[2].length < 6,
      children: [
        { label: '主营业务收入规模（万元）', value: '2022|prime_bus_profit' },
        { label: '营收规模（万元）', value: '2022|total_sales' },
        { label: '总利润规模（万元）', value: '2022|total_profit' },
        { label: '净利润规模（万元）', value: '2022|retained_profit' },
        { label: '资产总额规模（万元）', value: '2022|total_assets' },
        { label: '负债总额规模（万元）', value: '2022|total_liability' }
      ]
    },
    {
      label: '2021年经营数据',
      value: '2021',
      checkAll: checkedList[3].length === 6,
      indeterminate: checkedList[3].length > 0 && checkedList[3].length < 6,
      children: [
        { label: '主营业务收入规模（万元）', value: '2021|prime_bus_profit' },
        { label: '营收规模（万元）', value: '2021|total_sales' },
        { label: '总利润规模（万元）', value: '2021|total_profit' },
        { label: '净利润规模（万元）', value: '2021|retained_profit' },
        { label: '资产总额规模（万元）', value: '2021|total_assets' },
        { label: '负债总额规模（万元）', value: '2021|total_liability' }
      ]
    },
    {
      label: '2020年经营数据',
      value: '2020',
      checkAll: checkedList[4].length === 6,
      indeterminate: checkedList[4].length > 0 && checkedList[4].length < 6,
      children: [
        { label: '主营业务收入规模（万元）', value: '2020|prime_bus_profit' },
        { label: '营收规模（万元）', value: '2020|total_sales' },
        { label: '总利润规模（万元）', value: '2020|total_profit' },
        { label: '净利润规模（万元）', value: '2020|retained_profit' },
        { label: '资产总额规模（万元）', value: '2020|total_assets' },
        { label: '负债总额规模（万元）', value: '2020|total_liability' }
      ]
    },
    {
      label: '2019年经营数据',
      value: '2019',
      checkAll: checkedList[5].length === 6,
      indeterminate: checkedList[5].length > 0 && checkedList[5].length < 6,
      children: [
        { label: '主营业务收入规模（万元）', value: '2019|prime_bus_profit' },
        { label: '营收规模（万元）', value: '2019|total_sales' },
        { label: '总利润规模（万元）', value: '2019|total_profit' },
        { label: '净利润规模（万元）', value: '2019|retained_profit' },
        { label: '资产总额规模（万元）', value: '2019|total_assets' },
        { label: '负债总额规模（万元）', value: '2019|total_liability' }
      ]
    }
  ]

  const handleExport = () => {
    let selectedList = _.cloneDeep(dataList)
    const checkedFlatList = checkedList.flat()
    selectedList.forEach((first: any) => {
      first.children.forEach((second: any) => {
        if (checkedFlatList.includes(second.value)) {
          second.checked = true
        }
      })
      first.checked = first.children.some((second: { checked: any }) => second.checked)
      first.children = first.children.filter((second: { checked: any }) => second.checked)
    })
    selectedList = selectedList.filter((first: any) => first.checked)
    const params: any[] = []
    selectedList.forEach((first) => {
      if (first.value === '基本信息') {
        for (const item of first.children) {
          params.push({ [item.label]: item.value })
        }
      } else {
        const sub: any = {}
        first.children.forEach((second: { label: string | number; value: string }) => {
          sub[second.label] = second.value.split('|')[1]
        })
        params.push({
          [first.label]: {
            path: 'revenue_list',
            filter: `report_year=${first.value}`,
            sub
          }
        })
      }
    })
    callExportQuery(requestParams).then((res) => {
      callExportList({
        index: 'ads_lget_company_info',
        query: JSON.parse(res.data.query),
        column_mappings: params,
        filename: '企业探查',
        export_type: 'finance'
      }).then(() => {
        if (dataTotal > 5000) {
          message.success('提交成功，请在个人中心中查看审核结果')
        } else {
          message.success('导出成功，请注意查看邮箱')
        }
        handleCancel()
      })
    })
  }
  const handleOk = () => {
    const checkedFlatList = checkedList.flat()
    if (!checkedFlatList.length) {
      message.warning('请选择导出内容')
      return
    }
    if (dataTotal > 5000) {
      Modal.confirm({
        title: '导出确认？',
        content: '单次导出超出5000条，需要通过审批才能导出，是否继续？',
        onOk: () => {
          handleExport()
        }
      })
    } else {
      handleExport()
    }
  }
  const handleCancel = () => {
    setCheckedList([[], [], [], [], [], []])
    setIsModalOpen(false)
  }

  return {
    ExportModal: (
      <Modal title="选择导出内容" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={1000}>
        {dataList.map((first, index) => (
          <div key={first.value}>
            <Checkbox
              indeterminate={first.indeterminate}
              onChange={(e) => {
                setCheckedList((prev) => {
                  prev[index] = e.target.checked ? first.children.map((second: { value: any }) => second.value) : []
                  return [...prev]
                })
              }}
              checked={first.checkAll}>
              {first.label}
            </Checkbox>
            <CheckboxGroup
              options={first.children}
              value={checkedList[index]}
              onChange={(list) => {
                setCheckedList((prev) => {
                  prev[index] = list
                  return [...prev]
                })
              }}
            />
            <Divider />
          </div>
        ))}
      </Modal>
    ),
    showModal: () => {
      setCheckedList([[], [], [], [], [], []])
      setIsModalOpen(true)
    }
  }
}

export default useExportCompanyListModal
